// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */

	// 出入库单据列表
	async orderlistAction(){
		let page =JSON.parse(this.post('page'));
		let shopid = this.shop_userinfo.departmentid;

		let where ={
			'o.departmentid':shopid,
			'o.ordertype':['IN',[6,7]],
			'o.status':page.zt, 
			'o.order_sn': ['like', '%'+page.search+'%']
		}

		if (page.times && (page.times[0] != null && page.times[1] != null)) {

			let begintime = Math.floor(Date.parse(new Date(page.times[0]))/1000)

			let endtime = Math.floor(Date.parse(new Date(page.times[1]))/1000) + 86400 // 当天加上一天

			where['o.addtime'] = {'>=': begintime, '<': endtime}

		}  

		let list = await this.model('or_shop_stockorder')
		.alias('o')
		.field('o.*, a.name as aname, oa.name as oname')
		.join('`think_or_admin` a on a.id = o.operatorid')
		.join('`think_or_admin` oa on oa.id = o.auditorid')
		.where(where)
		.page(page.pages, page.limits)
		.order('o.id desc')
		.countSelect();

		return this.json(list);
	}
	// 领料单列表
	async pickorderlistAction(){
		/*let page = this.post();
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;*/
		let page = JSON.parse(this.post('page'));
		let zt = page.zt*1?[1,2]:[0];
		let shopid = this.shop_userinfo.departmentid;

		let where ={
			'o.departmentid':shopid,
			'o.status':['IN',zt],
			'o.ordertype':['IN',[8,9]], 
			'u.name|o.order_sn': ['like', '%'+page.search+'%']
		}

		if (page.times && (page.times[0] != null && page.times[1] != null)) {

			let begintime = Math.floor(Date.parse(new Date(page.times[0]))/1000)

			let endtime = Math.floor(Date.parse(new Date(page.times[1]))/1000) + 86400 // 当天加上一天

			where['o.addtime'] = {'>=': begintime, '<': endtime}

		}  

		let list = await this.model('or_shop_stockorder')
				.alias('o')
				.field('o.*, a.name as oname, oa.name as aname, u.name as uname')
				.join('`think_or_admin` a on a.id = o.operatorid')
				.join('`think_or_admin` oa on oa.id = o.auditorid')
				.join('`think_or_app_user` u on o.userid = u.id')
				.where(where)
				.page(page.pages, page.limits)
				.order('o.addtime desc')
				.countSelect();
		
		return this.json(list);
	}
	// 新增单据
	async addstockorderAction(){
		let data = JSON.parse(this.post('data'));
		let userinfo = this.shop_userinfo;
		// 组合成订单表和订单详细表
		let ordersn
		switch (Number(data.orderinfo.ordertype)) {
			case 6:
				ordersn = await this.getordersn('RKD',6)
				break
			case 7:
				ordersn = await this.getordersn('CKD',7)
				break
			case 8:
				ordersn = await this.getordersn('LLD',8)
				break
			case 9:
				ordersn = await this.getordersn('TLD',9)
				break
		}
		let orderdata = {
			order_sn: ordersn,
			departmentid: userinfo.departmentid,
			operatorid: userinfo.id,
			addtime: Math.round(Date.parse(new Date())/1000),
			ordertype: data.orderinfo.ordertype,
			status: 0,
			remarks: data.orderinfo.remarks,
			totalnum: data.orderinfo.totalnum,
			userid: data.userinfo && data.userinfo.id ? data.userinfo.id : 0,
			bumenid: data.userinfo && data.userinfo.bumenid ? data.userinfo.bumenid : 0
		}	

		// 插入到订单表
		let model = this.model('or_shop_stockorder');
		await model.transaction(async()=>{
			try{
				let resorder = await model.add(orderdata);
				let orderinfo = [];
				for (var i = data.list.length - 1; i >= 0; i--) {
					orderinfo.push({
						departmentid: userinfo.departmentid,
						orderid: resorder,
						goodsid: data.list[i].id,
						goodsname: data.list[i].name,
						num: data.list[i].num
					})
				};

				let resorderinfo = await this.model('or_shop_stockorderinfo').db(model.db()).addMany(orderinfo);

				if (resorder && resorderinfo) {
					model.commit();
					return this.success({data:200, info:'操作成功！'});
				} else {
					model.rollback();
					return this.fail("操作失败！");
				}
			}catch(e){
				model.rollback();
				return this.fail("操作失败！");
			}
		})
	}
	// 单据信息
	async orderinfoAction(){
		let id = this.post('id');
		let orderinfo = await this.model('or_shop_stockorder').where({id:id}).find();
		let orderlist = await this.model('or_shop_stockorderinfo').where({orderid:id}).select();
		let data = {
			orderinfo:orderinfo,
			orderlist:orderlist,
		}
		return this.json(data);
	}
	// 领料单信息
	async pickorderinfoAction(){
		let id = this.post('id');
		let orderinfo = await this.model('or_shop_stockorder')
		.alias('o')
		.field('o.*, u.name,s.name as departmentname')
		.join('`think_or_app_user` u on o.userid = u.id')
		.join('`think_or_department` s on s.id = u.departmentid')
		.where({'o.id':id})
		.find();
		let orderlist = await this.model('or_shop_stockorderinfo').where({orderid:id}).select();
		let data = {
			orderinfo:orderinfo,
			orderlist:orderlist,
		}
		return this.json(data);
	}

	// 审核单据
	async reviewstockorderAction(){
		let id = this.post('id');

		// 判断单据是否已经审核
		let orderinfo = await this.model('or_shop_stockorder').where({id:id}).find();
		let orderlist = await this.model('or_shop_stockorderinfo').where({orderid:id}).select();

		if(orderinfo.status == 1){
			return this.fail("该订单已经被审核！");
		}
		// 审核单据要做那些工作  1.改变单据状态，2.改变商品库存， 3.记录库存日志

		// 操作
		let model = this.model('or_shop_stockorder');
		await model.transaction(async()=>{
			try{
				let resorder = await model.where({id:id}).update({status:1,auditorid:this.shop_userinfo.id});

				let goodsdata = []
				let goodsdatalog = []
				let fu = orderinfo.ordertype == 6 || orderinfo.ordertype == 9 ? 1 : -1
				let ordertype
				switch (orderinfo.ordertype) {
					case 6:
						ordertype = 'RKD'
						break
					case 7:
						ordertype = 'CKD'
						break
					case 8:
						ordertype = 'LLD'
						break
					case 9:
						ordertype = 'TLD'
						break
				}

				for (var i = orderlist.length - 1; i >= 0; i--) {
					let goodsinfo = await this.model('or_shop_goods').db(model.db()).where({goodsid: orderlist[i].goodsid, shopid: orderinfo.departmentid}).find();
					goodsinfo.nums += orderlist[i].num*fu
					// 判断是否允许负库存
					if (goodsinfo.nums < 0) {
						model.rollback()
						let goods = await this.model('or_goods').db(model.db()).where({id: goodsinfo.goodsid}).find()
						return this.fail(goods.name + "库存不足！")
					}
					goodsdata.push(goodsinfo)
					goodsdatalog.push({
						departmentid: orderinfo.departmentid,
						goodsid: orderlist[i].goodsid,
						ordertype: ordertype,
						orderid: id,
						nums: orderlist[i].num*fu,
						addtime: orderinfo.addtime,
						posttime: Math.round(Date.parse(new Date())/1000)
					})
				};

				let resgoods = await this.model('or_shop_goods').db(model.db()).updateMany(goodsdata);
				let resgoodslog = await this.model('or_shop_goodslog').db(model.db()).addMany(goodsdatalog);

				if (resorder && resgoods && resgoodslog) {
					model.commit();
					return this.success({data:200, info:'操作成功！'});
				} else {
					model.rollback();
					return this.fail("操作失败！");
				}
			}catch(e){
				console.log(e)
				model.rollback();
				return this.fail("操作失败！");
			}
		})
	}

	// 删除单据
	async deletestockorderAction(){
		let id = this.post('id');

		// 判断单据是否已经审核
		let orderinfo = await this.model('or_shop_stockorder').where({id:id}).find();
		if(orderinfo.status == 1){
			return this.fail("该订单已经被审核，不能删除！");
		}

		//删除操作
		let model = this.model('or_shop_stockorder');
		await model.transaction(async()=>{
			try{
				let ores = await model.where({id:id}).delete();
				// 删除附属表
				let ires = await this.model('or_shop_stockorderinfo').db(model.db()).where({orderid:id}).delete();
				if (ores && ires) {
					model.commit();
					return this.success({data:200, info:'操作成功！'});
				} else {
					model.rollback();
					return this.fail("操作失败！");
				}
			}catch(e){
				await model.rollback();
				return this.fail("操作失败！");
			}
		});
	}

	// 获取商品的库存日志
	async getgoodslogsAction () {
		
		let pages = this.post('pages')
		let limits = this.post('limits')
		let goodsid = this.post('goodsid')

		let list = await this.model('or_shop_goodslog')
		.where({goodsid: goodsid, departmentid: this.shop_userinfo.departmentid})
		.page(pages, limits)
		.order('addtime desc')
		.countSelect()

		// 获取当前库存
		let goods = await this.model('or_shop_goods').where({goodsid: goodsid, shopid: this.shop_userinfo.departmentid}).find()
		let data = {
			goods: goods,
			list: list
		}
		return this.json(data);
	}
}